#!/bin/bash

# Vert.cj vs SeedHttp 性能对比测试脚本
# 使用wrk进行HTTP负载测试

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 测试配置
DURATION="30s"
THREADS=10
CONNECTIONS=2000
WARMUP_TIME=5

# 结果文件
RESULTS_DIR="benchmark_results"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
VERT_RESULT="${RESULTS_DIR}/vert_cj_${TIMESTAMP}.txt"
SEED_RESULT="${RESULTS_DIR}/seedhttp_${TIMESTAMP}.txt"
COMPARISON_REPORT="${RESULTS_DIR}/comparison_report_${TIMESTAMP}.md"

# 创建结果目录
mkdir -p ${RESULTS_DIR}

echo -e "${CYAN}🚀 Vert.cj vs SeedHttp 性能对比测试${NC}"
echo -e "${CYAN}========================================${NC}"
echo -e "测试配置:"
echo -e "  ⏱️  持续时间: ${DURATION}"
echo -e "  🧵 线程数: ${THREADS}"
echo -e "  🔗 连接数: ${CONNECTIONS}"
echo -e "  🔥 预热时间: ${WARMUP_TIME}s"
echo ""

# 检查wrk是否安装
if ! command -v wrk &> /dev/null; then
    echo -e "${RED}❌ wrk未安装，请先安装wrk工具${NC}"
    echo -e "macOS: brew install wrk"
    echo -e "Ubuntu: sudo apt-get install wrk"
    exit 1
fi

# 检查cjpm是否安装
if ! command -v cjpm &> /dev/null; then
    echo -e "${RED}❌ cjpm未安装，请先安装Cangjie开发环境${NC}"
    exit 1
fi

# 函数：等待服务器启动
wait_for_server() {
    local port=$1
    local name=$2
    echo -e "${YELLOW}⏳ 等待${name}服务器启动 (端口${port})...${NC}"
    
    for i in {1..30}; do
        if curl -s "http://localhost:${port}/api/status" > /dev/null 2>&1; then
            echo -e "${GREEN}✅ ${name}服务器已启动${NC}"
            return 0
        fi
        sleep 1
    done
    
    echo -e "${RED}❌ ${name}服务器启动超时${NC}"
    return 1
}

# 函数：运行性能测试
run_benchmark() {
    local port=$1
    local name=$2
    local result_file=$3
    
    echo -e "${BLUE}🔥 预热${name}服务器...${NC}"
    curl -s "http://localhost:${port}/api/status" > /dev/null
    curl -s "http://localhost:${port}/api/echo" -d "warmup" > /dev/null
    curl -s "http://localhost:${port}/api/benchmark" > /dev/null
    sleep ${WARMUP_TIME}
    
    echo -e "${PURPLE}📊 开始${name}性能测试...${NC}"
    echo "=== ${name} 性能测试结果 ===" > ${result_file}
    echo "测试时间: $(date)" >> ${result_file}
    echo "配置: ${THREADS}线程, ${CONNECTIONS}连接, ${DURATION}" >> ${result_file}
    echo "" >> ${result_file}
    
    # 测试不同端点
    echo "1. /api/status 端点测试:" >> ${result_file}
    wrk -t${THREADS} -c${CONNECTIONS} -d${DURATION} --latency "http://localhost:${port}/api/status" >> ${result_file} 2>&1
    echo "" >> ${result_file}
    
    echo "2. /api/benchmark 端点测试:" >> ${result_file}
    wrk -t${THREADS} -c${CONNECTIONS} -d${DURATION} --latency "http://localhost:${port}/api/benchmark" >> ${result_file} 2>&1
    echo "" >> ${result_file}
    
    echo "3. /api/echo 端点测试 (POST):" >> ${result_file}
    wrk -t${THREADS} -c${CONNECTIONS} -d${DURATION} --latency -s post_script.lua "http://localhost:${port}/api/echo" >> ${result_file} 2>&1
    echo "" >> ${result_file}
    
    echo -e "${GREEN}✅ ${name}测试完成${NC}"
}

# 创建POST测试脚本
cat > post_script.lua << 'EOF'
wrk.method = "POST"
wrk.body   = '{"test": "benchmark data", "timestamp": "2025-01-16"}'
wrk.headers["Content-Type"] = "application/json"
EOF

echo -e "${YELLOW}🏗️  编译项目...${NC}"
cjpm build

echo -e "${BLUE}🚀 启动Vert.cj服务器 (端口8080)...${NC}"
cjpm run --name vert.examples.final_demo &
VERT_PID=$!

# 等待Vert.cj服务器启动
if wait_for_server 8080 "Vert.cj"; then
    # 运行Vert.cj测试
    run_benchmark 8080 "Vert.cj" ${VERT_RESULT}
else
    echo -e "${RED}❌ Vert.cj服务器启动失败${NC}"
    kill ${VERT_PID} 2>/dev/null || true
    exit 1
fi

# 停止Vert.cj服务器
echo -e "${YELLOW}🛑 停止Vert.cj服务器...${NC}"
kill ${VERT_PID} 2>/dev/null || true
sleep 2

echo -e "${BLUE}🚀 启动SeedHttp风格服务器 (端口8081)...${NC}"
cjpm run --name vert.examples.seedhttp_benchmark &
SEED_PID=$!

# 等待SeedHttp服务器启动
if wait_for_server 8081 "SeedHttp"; then
    # 运行SeedHttp测试
    run_benchmark 8081 "SeedHttp" ${SEED_RESULT}
else
    echo -e "${RED}❌ SeedHttp服务器启动失败${NC}"
    kill ${SEED_PID} 2>/dev/null || true
    exit 1
fi

# 停止SeedHttp服务器
echo -e "${YELLOW}🛑 停止SeedHttp服务器...${NC}"
kill ${SEED_PID} 2>/dev/null || true
sleep 2

# 生成对比报告
echo -e "${CYAN}📋 生成性能对比报告...${NC}"
cat > ${COMPARISON_REPORT} << EOF
# Vert.cj vs SeedHttp 性能对比报告

**测试时间**: $(date)  
**测试配置**: ${THREADS}线程, ${CONNECTIONS}连接, ${DURATION}持续时间

## 测试环境
- **操作系统**: $(uname -s) $(uname -r)
- **CPU**: $(sysctl -n machdep.cpu.brand_string 2>/dev/null || grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)
- **内存**: $(sysctl -n hw.memsize 2>/dev/null | awk '{print $1/1024/1024/1024 "GB"}' || grep MemTotal /proc/meminfo | awk '{print $2/1024/1024 "GB"}')

## 架构对比

### Vert.cj架构特点
- 基于SeedHttp的高级封装
- 增强对象池系统
- 协程池管理（可配置）
- Keep-Alive连接复用
- 字节级HTTP处理优化

### SeedHttp原生架构特点
- 直接RequestContext处理
- 内置对象池系统
- 零拷贝字节操作
- 原生高性能连接管理
- 最小化抽象层

## 性能测试结果

### Vert.cj结果摘要
EOF

# 提取Vert.cj关键指标
if [ -f ${VERT_RESULT} ]; then
    echo "#### /api/status 端点" >> ${COMPARISON_REPORT}
    grep -A 10 "1. /api/status 端点测试:" ${VERT_RESULT} | grep -E "(Requests/sec|Transfer/sec|Latency)" >> ${COMPARISON_REPORT}
    echo "" >> ${COMPARISON_REPORT}
    
    echo "#### /api/benchmark 端点" >> ${COMPARISON_REPORT}
    grep -A 10 "2. /api/benchmark 端点测试:" ${VERT_RESULT} | grep -E "(Requests/sec|Transfer/sec|Latency)" >> ${COMPARISON_REPORT}
    echo "" >> ${COMPARISON_REPORT}
fi

echo "### SeedHttp结果摘要" >> ${COMPARISON_REPORT}

# 提取SeedHttp关键指标
if [ -f ${SEED_RESULT} ]; then
    echo "#### /api/status 端点" >> ${COMPARISON_REPORT}
    grep -A 10 "1. /api/status 端点测试:" ${SEED_RESULT} | grep -E "(Requests/sec|Transfer/sec|Latency)" >> ${COMPARISON_REPORT}
    echo "" >> ${COMPARISON_REPORT}
    
    echo "#### /api/benchmark 端点" >> ${COMPARISON_REPORT}
    grep -A 10 "2. /api/benchmark 端点测试:" ${SEED_RESULT} | grep -E "(Requests/sec|Transfer/sec|Latency)" >> ${COMPARISON_REPORT}
    echo "" >> ${COMPARISON_REPORT}
fi

cat >> ${COMPARISON_REPORT} << EOF

## 详细测试结果

### Vert.cj详细结果
详见: [${VERT_RESULT}](${VERT_RESULT})

### SeedHttp详细结果  
详见: [${SEED_RESULT}](${SEED_RESULT})

## 结论和建议

1. **性能对比**: 通过上述测试结果可以看出两种实现的性能差异
2. **架构选择**: 
   - 选择Vert.cj：需要更高级的抽象和更丰富的功能
   - 选择SeedHttp：追求极致性能和最小化开销
3. **优化建议**: 基于测试结果的具体优化建议

---
*测试报告生成时间: $(date)*
EOF

# 清理临时文件
rm -f post_script.lua

echo -e "${GREEN}✅ 性能对比测试完成！${NC}"
echo -e "${CYAN}📊 测试结果:${NC}"
echo -e "  📄 Vert.cj结果: ${VERT_RESULT}"
echo -e "  📄 SeedHttp结果: ${SEED_RESULT}"
echo -e "  📋 对比报告: ${COMPARISON_REPORT}"
echo ""
echo -e "${PURPLE}🔍 查看对比报告:${NC}"
echo -e "  cat ${COMPARISON_REPORT}"
